package controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import DAO.BookDetailsDAO;
import DAO.DAOFactory;
import DAO.NotFoundException;
import DAO.UserDAO;

import model.BookDetailsDTO;
import model.UserDTO;

/**
 * Servlet implementation class ApproveController
 */
@WebServlet("/ApproveController")
public class ApproveController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ApproveController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doProcess(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String textID = request.getParameter("id");
		Integer id = Integer.parseInt(textID);
		String status = request.getParameter("status");
		String comment = request.getParameter("comment");
		java.util.Date now = new java.util.Date();
		java.sql.Date modOn = new java.sql.Date(now.getTime());
		BookDetailsDTO done = null;
		BookDetailsDAO b = DAOFactory.loadInstance().getBookDetailsDAO();
		try{
			done = b.FindByBookingID(id);
			done.setComment(comment);
			done.setStatus(status);
			done.setModifiedOn(modOn);
		}
		catch(NotFoundException e){
			e.printStackTrace();
		}
		try{
			if(b!=null)
				b.update(done);
		}
		catch(NotFoundException e){
			e.printStackTrace();
		}
		
		RequestDispatcher rd = request.getRequestDispatcher("/ReviewController");
		try {
			rd.forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	private void doProcess(HttpServletRequest req, HttpServletResponse res){
		BookDetailsDTO toApprove;
		UserDTO user;
		BookDetailsDAO b = DAOFactory.loadInstance().getBookDetailsDAO();
		UserDAO d = DAOFactory.loadInstance().getUserDAO();
		
		try{
			String s = req.getParameter("book");
			Integer id = Integer.parseInt(s);
			toApprove = b.FindByBookingID(id);
			user = d.findbyId(toApprove.getBookedBy());
			req.setAttribute("processing", toApprove);
			req.setAttribute("user", user);
		}
		catch(NotFoundException e){
			e.printStackTrace();
		}
		RequestDispatcher rd = req.getRequestDispatcher("/ApproveBooking.jsp");
		try {
			rd.forward(req, res);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
